<template>
  <el-cascader
    popper-class="popperStyle"
    v-model="cascader"
    :options="departmentOptions"
    :props="cascaderProps"
    :show-all-levels="false"
    filterable
    clearable
    :debounce="500"
    :placeholder="props.placeholder"
    collapse-tags
    collapse-tags-tooltip
    :filter-method="filterMethod"
    @change="change"
  />
</template>

<script setup>
import { computed, reactive } from "vue";
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();
const departmentOptions = computed(() => {
  if (!commonStore.departmentOptions) {
    commonStore.getDepartmentList();
  }
  return commonStore.departmentOptions || [];
});
const props = defineProps({
  modelValue: [String, Number, Array],
  placeholder: {
    type: String,
    default: "请选择",
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  checkStrictly: {
    type: Boolean,
    default: true,
  },
  emitPath: {
    type: Boolean,
    default: false,
  },
});

const cascaderProps = reactive({
  emitPath: props.emitPath,
  multiple: props.multiple,
  label: "name",
  value: "id",
  children: "sub",
  checkStrictly: props.checkStrictly,
});

const filterMethod = (node, val) => {
  if (
    !!~node.text.indexOf(val) ||
    !!~node.text.toUpperCase().indexOf(val.toUpperCase())
  ) {
    return true;
  }
};

const cascader = computed(() => {
  return props.modelValue;
});

const emit = defineEmits(["update:modelValue", "changeName"]);
const change = (val) => {
  console.log(val);
  const selectedUserNames = Array.from(findUserNameById(departmentOptions.value, val));
  emit("update:modelValue", val || "");
  if (props.multiple) {
    emit("changeName", selectedUserNames);
  } else {
    emit("changeName", selectedUserNames[0]);
  }
};

const findUserNameById = (options, userIds) => {
  const selectedUserNames = new Set();

  const dfs = (node) => {
    if (!node) return;

    const nodeUserIds = Array.isArray(node.user_id) ? node.user_id : [node.user_id];

    if (Array.isArray(userIds)) {
      if (userIds.some((id) => nodeUserIds.includes(id))) {
        selectedUserNames.add(node.name);
      }
    } else {
      if (nodeUserIds.includes(userIds)) {
        selectedUserNames.add(node.name);
      }
    }

    if (node.sub && node.sub.length > 0) {
      for (const subNode of node.sub) {
        dfs(subNode);
      }
    }
  };

  for (const option of options) {
    dfs(option);
  }

  return selectedUserNames;
};
</script>

<style lang="scss">
.el-cascader__tags {
  z-index: 2;
}
</style>
